﻿using BasicInformation.ApiRead.Application.Command.Inventorys;
using BasicInformation.Domain;
using BasicInformation.Dtos;
using BasicInformation.ErrorCode;
using BasicInformation.Infrastructure.Implement;
using Dapper;
using MediatR;
using System.Text;

namespace BasicInformation.ApiRead.Application.Handler.Inventorys
{
    public class GetInventorysHandler : IRequestHandler<GetInventorysCommand, ApiPaging<InventorysDTO>>
    {
        private readonly DatabaseContext db;
        private readonly ILogger<GetInventorysHandler> logger;

        public GetInventorysHandler(DatabaseContext db,ILogger<GetInventorysHandler> logger)
        {
            this.db = db;
            this.logger = logger;
        }

        public async Task<ApiPaging<InventorysDTO>> Handle(GetInventorysCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<InventorysDTO> paging = new ApiPaging<InventorysDTO>();
            StringBuilder sql = new StringBuilder();
            StringBuilder countSql = new StringBuilder();

            // 构建主查询SQL
            sql.Append(@"SELECT
                  a.InventoryId,       
                  a.InventoryCode,        
                  b.ResultName,          
                  c.DepotName,            
                  d.ITypeName,           
                  a.IStartTime,       
                  a.IEndTime,          
                  a.ReceiveState,        
                  a.DispatchState,        
                  a.InventoryHandler,     
                  a.InventoryRemark   
                FROM
                  inventorysmodel a       
                  LEFT JOIN resultmodel b ON a.ResultId = b.ResultId  
                  LEFT JOIN depotmodel c ON a.DepotId = c.DepotId         
                  LEFT JOIN ITypemodel d ON a.ITypeId = d.ITypeId           
                WHERE
                  a.IsDel = 0 ");
 
            // 构建计数SQL
            countSql.Append(@"SELECT
                            COUNT(*) 
                            FROM
                            inventorysmodel
                            WHERE
                            IsDel = 0"); 
 
            // 添加查询条件
            if (!string.IsNullOrWhiteSpace(request.InventoryCode))
            {
                sql.Append(" AND InventoryCode=@InventoryCode"); 
                countSql.Append(" AND InventoryCode=@InventoryCode");
            }
            if (request.ResultId > 0)
            {
                sql.Append(" AND a.ResultId=@ResultId");
                countSql.Append(" AND ResultId=@ResultId");
            }
            if (request.DepotId > 0)
            {
                sql.Append(" AND a.DepotId=@DepotId");
                countSql.Append(" AND DepotId=@DepotId");
            }
            if (request.ITypeId > 0)
            {
                sql.Append(" AND a.ITypeId=@ITypeId");
                countSql.Append(" AND ITypeId=@ITypeId");
            }

            // 添加分页和排序
            sql.Append(" ORDER BY a.InventoryId LIMIT @size OFFSET @offset"); 
 
            // 准备查询参数
            var parameters = new
            {
                InventoryCode = request.InventoryCode,
                ResultId = request.ResultId,
                DepotId = request.DepotId,
                ITypeId = request.ITypeId,
                size = request.size,
                offset = (request.index - 1) * request.size,
            };

            try
            {
                // 执行分页查询
                var pageData = await db.DapperConnection.QueryAsync<InventorysDTO>(sql.ToString(), parameters);

                // 执行总数查询
                int totalCount = await db.DapperConnection.ExecuteScalarAsync<int>(countSql.ToString(), parameters);

                // 计算总页数
                int totalPage = (int)Math.Ceiling(totalCount / (double)request.size);

                // 设置返回结果
                paging.Msg = "库存盘点查询成功";
                paging.Code = ApiEnum.OK;
                paging.Data = pageData.ToList();
                paging.TotalCount = totalCount;
                paging.TotalPCount = totalPage;
            }
            catch (Exception ex)
            {
                // 记录错误日志
                logger.LogError(ex, "库存盘点查询失败 - SQL: {sql}, 参数: {@parameters}", sql.ToString(), parameters);
                paging.Code = ApiEnum.Fail;
                paging.Msg = "库存盘点查询失败，请稍后再试";
            }

            return paging;
        }
    }
}
